﻿using QuanLyGiaoVuDAL.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace QuanLyGiaoVuUI.Extensions.ExtendedAttributes
{
    public class GiangVienAuthorizeAttribute : FilterAttribute, IAuthorizationFilter
    {
        public bool ChiGiaoVu = false;

        public bool ReturnJson = false;

        public bool AllowAnonymous = false;

        public void OnAuthorization(AuthorizationContext filterContext)
        {
            var session  = filterContext.HttpContext.Session;
            NguoiDungDTO myInfo = new NguoiDungDTO();
            if (session["UserInfo"] != null)
            {
                myInfo = (NguoiDungDTO)session["UserInfo"];
            }
            else
                myInfo = null;

            if (!AllowAnonymous && !(myInfo != null && (((myInfo.VaiTro == 1 || myInfo.VaiTro == 0) && ChiGiaoVu == false) ||(myInfo.VaiTro == 0 && ChiGiaoVu == true))))
            {
                if (!ReturnJson)
                {
                    filterContext.Result = new RedirectResult("/DangNhapClient/GiangVienDangNhap");
                }
                else
                { 
                    JsonResult json = new JsonResult();
                    json.Data = new {
                        success = false,
                        message = "Chưa đăng nhập hoặc không có quyền truy cập."
                    };
                    filterContext.Result = json;
                }
            }
        }
    }
}